const { createServer } = require("http");
const { Server } = require("socket.io");
const requestIp = require("request-ip");

const httpServer = createServer();

const io = new Server(httpServer, {
  cors: {
    //解决跨域问题
    origin: "*",
    methods: ["GET", "POST"],
  },
});
const users = {};
const socketToRoom = {};

io.on("connection", (socket) => {
  let clientIP = requestIp.getClientIp(socket.request);
  console.log("客户端IP: " + clientIP);
  socket.on("join room", (roomID) => {
    if (users[roomID]) {
      const length = users[roomID].length;
      if (length === 100) {
        socket.emit("room full");
        return;
      }
      users[roomID].push(socket.id);
    } else {
      users[roomID] = [socket.id];
    }
    socketToRoom[socket.id] = roomID;
    const usersInThisRoom = users[roomID].filter((id) => id !== socket.id);
    socket.emit("all users", usersInThisRoom);
  });
  socket.on("sending signal", (payload) => {
    io.to(payload.userToSignal).emit("user joined", {
      signal: payload.signal,
      callerID: payload.callerID,
    });
  });
  socket.on("returning signal", (payload) => {
    io.to(payload.callerID).emit("receiving returned signal", {
      signal: payload.signal,
      id: socket.id,
    });
  });
  socket.on("disconnect", () => {
    const roomID = socketToRoom[socket.id];
    let room = users[roomID];
    if (room) {
      room = room.filter((id) => id !== socket.id);
      users[roomID] = room;
      socket.broadcast.emit("user left", socket.id);
    }
  });
});
httpServer.listen(3001, function () {
  console.log("http://127.0.0.1:3001");
});
